<template>
  <div>
    <a-spin :spinning="isLoading || isLoadingOther">
      <a-form :model="editForm" name="edit-form" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" autocomplete="off"
        @finish="editPost">
        <a-form-item label="捐赠项目" name="donation_id" show-search option-filter-prop="search-value" :rules="[{ required: true, message: '请选择捐赠项目' }]">
          <a-select v-model:value="editForm.donation_id" placeholder="请选择捐赠项目">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="(item, index) in donationList" :key="index" :value="index" :search-value="item">{{ item
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="发布人" name="author" :rules="[{ required: true, message: '请输入发布人' }]">
          <a-input v-model:value="editForm.author" placeholder="请输入发布人" />
        </a-form-item>
        <a-form-item label="标题（中文）" name="title" :rules="[{ required: true, message: '请输入标题（中文）' }]">
          <a-input v-model:value="editForm.title" placeholder="请输入标题（中文）" />
        </a-form-item>
        <a-form-item label="标题（英文）" name="title_us" :rules="[{ required: true, message: '请输入标题（英文）' }]">
          <a-input v-model:value="editForm.title_us" placeholder="请输入标题（英文）" />
        </a-form-item>
        <a-form-item label="标题（繁体）" name="title_hk" :rules="[{ required: true, message: '请输入标题（繁体）' }]">
          <a-input v-model:value="editForm.title_hk" placeholder="请输入标题（繁体）" />
        </a-form-item>
        <a-form-item label="发布内容（中文）" name="content" :rules="[{ required: true, message: '请输入发布内容（中文）' }]">
          <a-textarea v-model:value="editForm.content" :rows="4" placeholder="请输入发布内容（中文）" />
        </a-form-item>
        <a-form-item label="发布内容（英文）" name="content_us" :rules="[{ required: true, message: '请输入发布内容（英文）' }]">
          <a-textarea v-model:value="editForm.content_us" :rows="4" placeholder="请输入发布内容（英文）" />
        </a-form-item>
        <a-form-item label="发布内容（繁体）" name="content_hk" :rules="[{ required: true, message: '请输入发布内容（繁体）' }]">
          <a-textarea v-model:value="editForm.content_hk" :rows="4" placeholder="请输入发布内容（繁体）" />
        </a-form-item>
        <a-form-item label="项目进展日期" name="add_date" :rules="[{ required: true, message: '请选择项目进展日期' }]">
          <a-date-picker v-model:value="editForm.add_date" value-format="YYYY-MM-DD" placeholder="请选择项目进展日期"
            style="width: 100%;" />
        </a-form-item>
        <a-form-item label="图片" name="img" :rules="[{ required: true, message: '请上传图片' }]">
          <a-upload v-model:value="editForm.img" name="img" list-type="picture-card" class="avatar-uploader"
            :show-upload-list="false" :action="`${uploadUrl}donation_progress`" @change="uploadFileChange"
            :accept="'image/*'" :headers="uploadAddHeaders">
            <img v-if="editForm.img" :src="imgDomainUrl + editForm.img" style="max-width: 100%;max-height: 100%;" />
            <div v-else>
              <loading-outlined v-if="isLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-button type="primary" html-type="submit">立即提交</a-button>
          <a-button @click="editCancel" style="margin-left:10px;">取消</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';
import { message } from 'ant-design-vue';
import { editDonationProgress, getDonationListAll, getDonationProgressDetail } from "@/api/admin";   //引入api
import { useRouter, useRoute } from 'vue-router';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';

const { uploadUrl, uploadAddHeaders } = inject('uploadInfo');  // 依赖注入--上传文件有关的配置
const { imgDomainUrl } = inject('imgDomainUrl');  // 依赖注入--文件、图片前的域名
const router = useRouter();
const route = useRoute();

const isLoading = ref(false);    // 控制loading
const isLoadingOther = ref(false);    // 控制loading

const editForm = ref({});  // 编辑表单

const id = ref(route.query.id);  // 参数id
//根据参数id获取数据
const getUrlId = () => {
  const { checkURLParamsId } = inject('checkURLParamsId');  // 依赖注入--验证参数id正确性
  if (checkURLParamsId(id)) {
    isLoading.value = true;
    getDonationProgressDetail({ id: id.value }).then((res) => {
      isLoading.value = false;
      if (res === false) return;

      editForm.value.id = res.data.id;
      editForm.value.donation_id = String(res.data.donation_id);
      editForm.value.author = res.data.author;
      editForm.value.title = res.data.title;
      editForm.value.title_us = res.data.title_us;
      editForm.value.title_hk = res.data.title_hk;
      editForm.value.content = res.data.content;
      editForm.value.content_us = res.data.content_us;
      editForm.value.content_hk = res.data.content_hk;
      editForm.value.add_date = res.data.add_date;
      editForm.value.img = res.data.img;
    }).catch((rej) => {
      isLoading.value = false;
      message.error('获取数据失败：' + rej);
      editCancel();
    });
  }
}

// 获取接口数据列表
const editPost = () => {
  isLoading.value = true;

  if (editForm.value.img === undefined || editForm.value.img === null || editForm.value.img === '') {
    message.error('请上传图片');
    isLoading.value = false;
    return;
  }

  editDonationProgress(editForm.value).then((res) => {
    if (res === false) return;

    message.success('操作成功，即将跳转……');
    setTimeout(() => { editCancel() }, 1000);
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 跳转到列表页
const editCancel = () => {
  isLoading.value = false;
  router.replace('/admin/donation_progress/index');
}

const donationList = ref([]); // 捐赠项目列表
// 获取捐赠项目列表
const getDonationList = () => {
  isLoadingOther.value = true;
  getDonationListAll({}).then((res) => {
    isLoadingOther.value = false;
    if (res === false) return;

    donationList.value = res.data;  //数据列表
  });
};

// 上传图片
const uploadFileChange = info => {
  if (info.file.status === 'uploading') {
    isLoading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    isLoading.value = false;
    if (info.file.response.code === 0) {
      editForm.value.img = info.file.response.data.down_path;
    } else {
      message.error(info.file.response.message);
    }
  }
  if (info.file.status === 'error') {
    isLoading.value = false;
    message.error('上传文件出错，请重新上传！');
  }
};

// 页面加载完成后，获取数据列表
onMounted(() => {
  getUrlId();
  getDonationList();
})
</script>

<style scoped></style>